#! /bin/sh

set -ex

srcdir="$(dirname "$0")"
test -z "$srcdir" && srcdir=.

cd "$srcdir"

clone_repo_commit() {
    if test -d $2/.git; then
        git -C $2 reset --hard
        git -C $2 clean -fd
        if ! git -C $2 checkout $3; then
            rm -rf $2
        fi
    else
        if test -d $2; then
            echo "error: '$2' is not a Git repository"
            exit 1
        fi
    fi
    if ! test -d $2; then
        git clone $1 $2
        git -C $2 checkout $3
    fi
}

download_by_hash() {
    DOWNLOAD_COMMAND="curl -Lo"
    if ! command -v $DOWNLOAD_COMMAND >/dev/null 2>&1; then
        DOWNLOAD_COMMAND="wget -O"
        if ! command -v $DOWNLOAD_COMMAND >/dev/null 2>&1; then
            echo "error: Neither curl nor wget found"
            exit 1
        fi
    fi
    SHA256_COMMAND="sha256sum"
    if ! command -v $SHA256_COMMAND >/dev/null 2>&1; then
        SHA256_COMMAND="sha256"
        if ! command -v $SHA256_COMMAND >/dev/null 2>&1; then
            echo "error: Cannot find sha256(sum) command"
            exit 1
        fi
    fi
    if ! test -f $2 || ! $SHA256_COMMAND $2 | grep $3 >/dev/null 2>&1; then
        rm -f $2
        mkdir -p $2 && rm -rf $2
        $DOWNLOAD_COMMAND $2 $1
        if ! $SHA256_COMMAND $2 | grep $3 >/dev/null 2>&1; then
            echo "error: Cannot download file '$2' by hash"
            exit 1
        fi
    fi
}

if ! test -f version; then
    clone_repo_commit \
        https://github.com/osdev0/freestanding-headers.git \
        freestanding-headers \
        f890bb927859719061fe020119f3d5439d90aecf

    download_by_hash \
        https://github.com/osdev0/cc-runtime/raw/dcdf5d82973e77edee597a047a3ef66300903de9/cc-runtime.c \
        c/cc-runtime.c \
        199907f5303ab15a963377fabcc1f2ee736e4ed18d54c59aab08345aa5485e8a

    clone_repo_commit \
        https://github.com/mintsuki/flanterm.git \
        c/flanterm \
        ef07a10cc38b34aa003d17be97a9f3542e275069

    clone_repo_commit \
        https://github.com/v-unikernel/mlibc.git \
        mlibc \
        a20b6dbb0af6c19ba7accc70f912f817a158b051
fi
